﻿/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.projects.xenia;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Calendar;


import com.projects.xenia.add_activities.Activity_ExtReports;
import com.projects.xenia.add_activities.Activity_Messages;
import com.projects.xenia.database_classes.SqlDataBase;
import com.projects.xenia.documents_activities.Activity_Task;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.journals_activities.Activity_Journal_Blanks;
import com.projects.xenia.journals_activities.Activity_Journal_Orders;
import com.projects.xenia.journals_activities.Activity_Journal_Payments;
import com.projects.xenia.journals_activities.Activity_Journal_PhotoReports;
import com.projects.xenia.journals_activities.Activity_Journal_Returns;
import com.projects.xenia.journals_activities.Activity_Journal_Tasks;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;

import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;




public class MainActivity extends ListActivity {	
	
	// global variables
    private static ArrayList<main_menu_item_structure> XR = new ArrayList<main_menu_item_structure> ();
    private static main_menu_item_structure X;    
    private static boolean lCreate;
    private static EfficientAdapter lAdapter;
    
    private static final int IDA_EXCHANGE = 13;
 
    
       // structures
    static class main_menu_item_structure {
    	
    	private int itemicon;
    	private String itemtext;
    	
    	private String itemmaintext;
    	private String iteminvoicetext;
    	private String itemaddtext;
    	
    }
        
    // bindings
    private static class EfficientAdapter extends BaseAdapter {
    	
        private LayoutInflater mInflater;        

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
           
           }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return XR.size();
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.main_form, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);

                holder.TextViewMainState = (TextView) convertView.findViewById(R.id.TextViewMainState);
                holder.TextViewInvoiceState = (TextView) convertView.findViewById(R.id.TextViewInvoiceState);
                holder.TextViewAddState = (TextView) convertView.findViewById(R.id.TextViewAddState);
                
                holder.stateView1 = (ImageView) convertView.findViewById(R.id.mainstatepic);
                holder.stateView2 = (ImageView) convertView.findViewById(R.id.invoicestatepic);
                
                convertView.setTag(holder);
                
            } else {
            	
               
                holder = (ViewHolder) convertView.getTag();
                
            }

                                      
            holder.text.setText(XR.get(position).itemtext);
            holder.icon.setImageResource(XR.get(position).itemicon);
            
            String maintext = XR.get(position).itemmaintext;
            String invoiceText = XR.get(position).iteminvoicetext;
            String itemaddtext = XR.get(position).itemaddtext;
            
            holder.TextViewMainState.setText(maintext);
            holder.TextViewInvoiceState.setText(invoiceText);
            holder.TextViewAddState.setText(itemaddtext);
            
            if ((maintext==null)||maintext.equals("")){
            	holder.stateView1.setVisibility(View.INVISIBLE);
            }
            else
            {
            	holder.stateView1.setVisibility(View.VISIBLE);
            }
            
            if ((invoiceText==null)||invoiceText.equals("")){
            	holder.stateView2.setVisibility(View.INVISIBLE);
            }
            else
            {
            	holder.stateView2.setVisibility(View.VISIBLE);
            }

            return convertView;
            
        }

        static class ViewHolder {
            TextView text;
            ImageView icon;
            TextView TextViewMainState;
            TextView TextViewInvoiceState;
            TextView TextViewAddState;
            ImageView stateView1;
            ImageView stateView2;
        }
        
    }

	private SqlDataBase DBE;
    
	private boolean CheckLastUpdate () {
		
		boolean _result = false;
		
		if (MainGlobalModule.ConstantsCollection.get("OfflineTime")!=null) {
			long _lastupdatetime = Long.parseLong(MainGlobalModule.SettingsCollection.get("LastUpdate")); 
			long _currenttime = Calendar.getInstance().getTimeInMillis();		
			long _offlinetime = 100000*36*Long.parseLong(MainGlobalModule.ConstantsCollection.get("OfflineTime"));			
			if ((_lastupdatetime+_offlinetime)>_currenttime) {				
				_result = !_result;
			}
		}
		
		return _result;
		
	}
	
	
    // main_form_menu select item 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	
    	Intent intent = new Intent();
    	
    	if (!CheckLastUpdate ()) {
    		if (position<12) {
    			Toast.makeText(this, "Истекло время автономной работы ! необходима обновление данных.", Toast.LENGTH_SHORT).show();
    			return;
    		}
    	}
    	
    	
    	switch (position){
    	
    	case 0:intent.setClass(this,MainGoodsCatalogActivity.class);startActivityForResult(intent, 0);break;
    	
    	case 1:intent.setClass(this,MainCustomersListActivity.class);startActivityForResult(intent, 0);break;
    	
    	case 2:intent.setClass(this,MainRouteListActivity.class);startActivityForResult(intent, 0);break;
    	
    	case 3:intent.setClass(this,MainDebtsListActivity.class);startActivityForResult(intent, 0);break;
    	
    	case 4:intent.setClass(this,Activity_Journal_Orders.class);startActivityForResult(intent, 0);break;
    	
    	case 5:intent.setClass(this,Activity_Journal_Payments.class);startActivityForResult(intent, 0);break;
    	
    	case 6:intent.setClass(this,Activity_Journal_Returns.class);startActivityForResult(intent, 0);break;    	
    	
    	case 7:intent.setClass(this,Activity_Journal_Tasks.class);startActivityForResult(intent, 0);break;
    	
    	case 8:intent.setClass(this,Activity_Journal_PhotoReports.class);startActivityForResult(intent, 0);break;
    	
    	case 9:intent.setClass (this,Activity_Journal_Blanks.class);startActivityForResult(intent, 0);break;
    	
    	case 10:intent.setClass(this, Activity_ExtReports.class);startActivityForResult(intent, 0);break;
    	
    	case 11:intent.setClass(this, Activity_Messages.class);startActivityForResult(intent, 0);break;
    	
    	case 12:intent.setClass(this,MainExchangeActivity.class);startActivityForResult(intent, IDA_EXCHANGE);break;
    	
    	case 13:intent.setClass(this,MainSettingsActivity.class);startActivityForResult(intent, 0);break;

    	//case 14:intent.setClass(this,MainInfoActivity.class);startActivityForResult(intent, 0);break;
    	
    	case 15:android.os.Process.killProcess(android.os.Process.myPid());break;
    	
    	}
    	
    }
    
    // menu
    public boolean onCreateOptionsMenu (Menu menu){  
    	menu.add(Menu.NONE,1,Menu.NONE,"Помощь").setIcon(R.drawable.st_info);
    	menu.add(Menu.NONE,2,Menu.NONE,"Выход").setIcon(R.drawable.st_exit);
		return true;    	
    }
    
    public boolean onOptionsItemSelected (MenuItem item){
    	switch (item.getItemId()) {
    		case 2:    			 
    			android.os.Process.killProcess(android.os.Process.myPid());    			
    			return true;
    	}
    		
    			return false;    	
    	    
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);   
 
        requestWindowFeature(Window.FEATURE_NO_TITLE);            
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
          
        if (!lCreate) {
        	
        	DBE = new SqlDataBase ();
        	DBE.InitializeDataBase ();        	
        	CreateMainForm ();
        	CreateMainFormIni ();   
        	
        	
        	}
        

        getListView().setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);
    	getListView().setScrollingCacheEnabled(false);
    	getListView().setCacheColorHint(Color.TRANSPARENT);
    	getListView().requestFocus(0);
    	
        File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.StoragePath,"wallpaper"));        
        if (ImgPath.exists()==true) {
        	Drawable Img = Drawable.createFromPath(ImgPath.getAbsolutePath());
            getListView().setBackgroundDrawable(Img);
        }
        else
        {
        	getListView().setBackgroundResource(R.drawable.wallpaper);
        }
        	
        	setListAdapter(lAdapter);
        	
        }   
        
    @Override
    public void onResume(){    	
        super.onResume();  
        lCreate = true;
    }
    
    private void CreateMainForm () {
    	
    	int CountNonSendedDocuments;
    	int CountNonDeletedDocuments; 
    	int CountNonInvoiceDocuments;
    	double SumNonDeletedDocuments;
    	
    	XR.clear();
    	
    	X = new main_menu_item_structure ();
        X.itemtext = "Товары";
        X.itemicon = R.drawable.st_goods;        
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Клиенты";
        X.itemicon = R.drawable.st_customers;                
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Маршрут";
        X.itemicon = R.drawable.st_route;        
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Долги";
        X.itemicon = R.drawable.st_debts;        
        XR.add(X);        
        
        X = new main_menu_item_structure ();
        X.itemtext = "Заказы";
        X.itemicon = R.drawable.st_orders;  
        CountNonSendedDocuments = GetCountNonSendedDocuments ("xdoc_orders_h");
        if (CountNonSendedDocuments>0) {
        	X.itemmaintext = String.format("(%d)", CountNonSendedDocuments);
        }        
        
        SumNonDeletedDocuments = GetNonDeletedDocumentsData ("xdoc_orders_h","total_ordersum");
        if (SumNonDeletedDocuments>0) {
        	X.itemaddtext = String.format("Сумма:%.2f", SumNonDeletedDocuments);
        }        
        CountNonInvoiceDocuments = GetCountNonInvoiceDocuments ("xdoc_orders_h");
        if (CountNonInvoiceDocuments>0) {
        	X.iteminvoicetext = String.format("(%d)", CountNonInvoiceDocuments);
        }        
        XR.add(X);        
        
        X = new main_menu_item_structure ();
        X.itemtext = "Оплаты";
        X.itemicon = R.drawable.st_payments;        
        CountNonSendedDocuments = GetCountNonSendedDocuments ("xdoc_payments_h");
        if (CountNonSendedDocuments>0) {
        	X.itemmaintext = String.format("(%d)", CountNonSendedDocuments);
        }        
        SumNonDeletedDocuments = GetNonDeletedDocumentsData ("xdoc_payments_h","total_paymentsum");
        if (SumNonDeletedDocuments>0) {
        	X.itemaddtext = String.format("Сумма:%.2f", SumNonDeletedDocuments);
        }
        CountNonInvoiceDocuments = GetCountNonInvoiceDocuments ("xdoc_payments_h");
        if (CountNonInvoiceDocuments>0) {
        	X.iteminvoicetext = String.format("(%d)", CountNonInvoiceDocuments);
        }        
        XR.add(X);        
        
        X = new main_menu_item_structure ();
        X.itemtext = "Возвраты";
        X.itemicon = R.drawable.st_returns;
        CountNonSendedDocuments = GetCountNonSendedDocuments ("xdoc_returns_h");
        if (CountNonSendedDocuments>0) {
        	X.itemmaintext = String.format("(%d)", CountNonSendedDocuments);
        }        
        SumNonDeletedDocuments = GetNonDeletedDocumentsData ("xdoc_returns_h","total_returnsum");
        if (SumNonDeletedDocuments>0) {
        	X.itemaddtext = String.format("Сумма:%.2f", SumNonDeletedDocuments);
        }
        CountNonInvoiceDocuments = GetCountNonInvoiceDocuments ("xdoc_returns_h");
        if (CountNonInvoiceDocuments>0) {
        	X.iteminvoicetext = String.format("(%d)", CountNonInvoiceDocuments);
        }
        XR.add(X);        
        
        X = new main_menu_item_structure ();        
        X.itemtext = "Задачи";
        X.itemicon = R.drawable.st_tasks;        
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Фотоотчет";
        X.itemicon = R.drawable.st_photos;        
        CountNonSendedDocuments = GetCountNonSendedDocuments ("xdoc_photoreports_h");
        if (CountNonSendedDocuments>0) {
        	X.itemmaintext = String.format("(%d)", CountNonSendedDocuments);
        }        
        int CountNonSendedPhoto = GetCountNonSendedPhoto ();
        if (CountNonSendedPhoto>0) {
        	X.iteminvoicetext = String.format("(%d)", CountNonSendedPhoto);
        }        
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Анкетирование";
        X.itemicon = R.drawable.st_info;
        CountNonSendedDocuments = GetCountNonSendedDocuments ("xdoc_blanks_h");
        if (CountNonSendedDocuments>0) {
        	X.itemmaintext = String.format("(%d)", CountNonSendedDocuments);
        }        
        XR.add(X); 
        
        X = new main_menu_item_structure ();
        X.itemtext = "Отчеты";
        X.itemicon = R.drawable.ic_reportsmain;
        XR.add(X);  
        
        X = new main_menu_item_structure ();
        X.itemtext = "Сообщения";
        X.itemicon = R.drawable.ic_messages;
        int UnreadMessagesValues = GetNonReadedMessages ();
        if (UnreadMessagesValues>0) {
        	X.itemmaintext = String.format("(%d)", UnreadMessagesValues);
        }
        XR.add(X);  
        
        X = new main_menu_item_structure ();
        X.itemtext = "Обмен данными";
        X.itemicon = R.drawable.st_exchange;        
        XR.add(X);        
        
        X = new main_menu_item_structure ();
        X.itemtext = "Настройки";
        X.itemicon = R.drawable.st_preferences;        
        XR.add(X);        
        
        X = new main_menu_item_structure ();
        X.itemtext = "Информация";
        X.itemicon = R.drawable.st_info;        
        XR.add(X);
        
        X = new main_menu_item_structure ();
        X.itemtext = "Выход";
        X.itemicon = R.drawable.st_exit;        
        XR.add(X);
        
    }    
   
    
    private void CreateMainFormIni () {
    	
    	lAdapter = new EfficientAdapter(this);
        
        setListAdapter(lAdapter);
	    
        MainGlobalModule.Cntx = this;
        
        MainGlobalModule.SettingsCollection_Initialize();
        MainGlobalModule.ConstantsCollection_Initialize();        
        
        MainGlobalModule.SettingsCollection_Update("DeviceId", GetDeviceId ());        
        
        try {
	    	
	    	File mdirectory = new File(MainGlobalModule.StoragePath);				
			File ipFile = new File(mdirectory, "ipconfig.txt");
			if (ipFile.exists()) {				
				StringBuilder stringBuilder = new StringBuilder();
			    String line;
			    BufferedReader in;
			    in = new BufferedReader(new FileReader(ipFile));			    
			    while ((line = in.readLine()) != null) stringBuilder.append(line);
			    in.close();			            
				ipFile.delete();
				MainGlobalModule.SettingsCollection_Update("PrimaryWebServiceURL",stringBuilder.toString());
				
		    }			
				
		} catch (Exception e) {
			
		}
        
    }

    private int GetCountNonSendedDocuments (String TableString) {    
		
    	int DocCount = 0;
    	
    	Cursor TotalCursor = MainGlobalModule.DBE.rawQuery("select count (*) from "+TableString+" a where date(a.date_create) = date('now') and a.state < 2 ", null);
    	if (TotalCursor.getCount()>0) {				
    		TotalCursor.moveToFirst();
    		DocCount = TotalCursor.getInt(0);
    		TotalCursor.close();
    	}
    	
    	return (DocCount);
    
    	}
    
    
    private int GetCountNonSendedPhoto () {    
		
    	int DocCount = 0;
    	
    	Cursor TotalCursor = MainGlobalModule.DBE.rawQuery("select count (*) from xdoc_photoreports_t where sended = 0", null);
    	if (TotalCursor.getCount()>0) {				
    		TotalCursor.moveToFirst();
    		DocCount = TotalCursor.getInt(0);
    		TotalCursor.close();
    	}
    	
    	return (DocCount);
    
    	}
   
    private int GetCountNonInvoiceDocuments (String TableString) {    
		
    	int DocCount = 0;
    	
    	Cursor TotalCursor = MainGlobalModule.DBE.rawQuery("select count (*) from "+TableString+" a where date(a.date_create) = date('now') and a.state in (1,5,13)", null);
    	if (TotalCursor.getCount()>0) {				
    		TotalCursor.moveToFirst();
    		DocCount = TotalCursor.getInt(0);
    		TotalCursor.close();
    	}
    	
    	return (DocCount);
    
    	}
    
    
    private int GetNonReadedMessages () {    
		
    	int DocCount = 0;
    	
    	Cursor TotalCursor = MainGlobalModule.DBE.rawQuery("select count (*) from xref_messages where id not in (select message_id from xdoc_ReadedMessages)", null);
    	if (TotalCursor.getCount()>0) {				
    		TotalCursor.moveToFirst();
    		DocCount = TotalCursor.getInt(0);
    		TotalCursor.close();
    	}
    	
    	return (DocCount);
    
    	}    
    
    private double GetNonDeletedDocumentsData (String TableString,String Field) {    
		
    	double DocCount = 0.0;
    	
    	Cursor TotalCursor = MainGlobalModule.DBE.rawQuery("select sum ("+Field+") from "+TableString+" a where date(a.date_create) = date('now') and a.state in (1,5,13,29)", null);
    	if (TotalCursor.getCount()>0) {				
    		TotalCursor.moveToFirst();
    		DocCount = TotalCursor.getDouble(0);
    		TotalCursor.close();
    	}
    	
    	return (DocCount);
    
    	}    
    
    private String GetDeviceId () {
    	
    	String DeviceId = "";    	
    	final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);    	   
    	DeviceId = tm.getDeviceId();
    	if (DeviceId==null) {
    		DeviceId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); 
    	}
	    return (DeviceId);	    
    }
 
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			  				
    			return false;
    			
    		
    	}	
		
		return super.onKeyDown(keyCode, event);
	}
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	
    	CreateMainForm ();
    	lAdapter.notifyDataSetChanged();
    	
    	switch (requestCode) {
		case IDA_EXCHANGE:
			if (GetNonReadedMessages ()>0) {
				Intent intent = new Intent();
				intent.setClass(this, Activity_Messages.class);
				startActivityForResult(intent, 0);
			}
			break;

		default:
			break;
		}
    	
    }
}







